import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import queue
import time
import multiprocessing
from datetime import datetime
from core.file_validator import FileValidator
from core.video_processor import VideoProcessor
from core.file_manager import FileManager
from core.process_manager import VideoProcessManager

class MainWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("音视频分离工具")
        self.root.geometry("1000x800")
        
        # 初始化核心组件
        self.video_processor = VideoProcessor()
        self.file_manager = FileManager()
        self.process_manager = VideoProcessManager()
        self.file_validator = FileValidator()
        
        # 变量初始化
        self.input_folder_var = tk.StringVar()
        self.output_folder_var = tk.StringVar()
        self.parallel_count_var = tk.IntVar(value=3)
        self.resolution_var = tk.StringVar(value="原分辨率")  # 改为原分辨率
        self.modify_resolution_var = tk.BooleanVar(value=False)
        self.progress_var = tk.DoubleVar()
        
        # 文件列表相关
        self.file_items = {}
        self.file_status = {}
        self.processing_files = set()
        
        # 处理状态
        self.processing = False
        self.completed_count = 0
        self.total_files = 0
        self.processing_start_time = None
        self.first_update_time = None
        
        # 解析状态
        self.parse_completed_count = 0
        self.parse_total_files = 0
        self.parse_video_info_list = []
        self.parse_processing = False
        
        # 设置UI
        self.setup_ui()
        
        # 检查FFmpeg
        if not self.video_processor.check_ffmpeg_available():
            messagebox.showerror("错误", "未检测到FFmpeg，请先安装FFmpeg")
    
    def setup_ui(self):
        """设置用户界面"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        
        # 输入文件夹选择
        ttk.Label(main_frame, text="输入文件夹:").grid(row=0, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.input_folder_var, width=50).grid(row=0, column=1, sticky=(tk.W, tk.E), padx=5, pady=5)
        ttk.Button(main_frame, text="浏览", command=self.select_input_folder).grid(row=0, column=2, padx=5, pady=5)
        
        # 输出文件夹选择
        ttk.Label(main_frame, text="输出文件夹:").grid(row=1, column=0, sticky=tk.W, pady=5)
        ttk.Entry(main_frame, textvariable=self.output_folder_var, width=50).grid(row=1, column=1, sticky=(tk.W, tk.E), padx=5, pady=5)
        ttk.Button(main_frame, text="浏览", command=self.select_output_folder).grid(row=1, column=2, padx=5, pady=5)
        
        # 处理选项框架
        options_frame = ttk.LabelFrame(main_frame, text="处理选项", padding="5")
        options_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5)
        
        # 第一行：保存选项
        save_frame = ttk.Frame(options_frame)
        save_frame.grid(row=0, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=2)
        
        ttk.Label(save_frame, text="保存选项:").grid(row=0, column=0, sticky=tk.W, padx=5)
        
        self.save_audio_var = tk.BooleanVar(value=True)
        self.save_video_var = tk.BooleanVar(value=True)
        self.save_subtitles_var = tk.BooleanVar(value=False)
        
        ttk.Checkbutton(save_frame, text="音频", 
                       variable=self.save_audio_var).grid(row=0, column=1, sticky=tk.W, padx=5)
        ttk.Checkbutton(save_frame, text="视频", 
                       variable=self.save_video_var).grid(row=0, column=2, sticky=tk.W, padx=5)
        ttk.Checkbutton(save_frame, text="字幕", 
                       variable=self.save_subtitles_var).grid(row=0, column=3, sticky=tk.W, padx=5)
        
        # 第二行：字幕处理选项
        subtitle_frame = ttk.Frame(options_frame)
        subtitle_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=2)
        
        ttk.Label(subtitle_frame, text="字幕处理:").grid(row=0, column=0, sticky=tk.W, padx=5)
        
        self.remove_subtitles_var = tk.BooleanVar(value=False)
        self.remove_hardcoded_subtitles_var = tk.BooleanVar(value=False)
        
        ttk.Checkbutton(subtitle_frame, text="移除内嵌字幕", 
                       variable=self.remove_subtitles_var).grid(row=0, column=1, sticky=tk.W, padx=5)
        ttk.Checkbutton(subtitle_frame, text="移除硬编码字幕", 
                       variable=self.remove_hardcoded_subtitles_var).grid(row=0, column=2, sticky=tk.W, padx=5)
        
        # 第三行：分辨率选项
        resolution_frame = ttk.Frame(options_frame)
        resolution_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=2)
        
        ttk.Label(resolution_frame, text="分辨率:").grid(row=0, column=0, sticky=tk.W, padx=5)
        
        ttk.Checkbutton(resolution_frame, text="修改视频分辨率", 
                       variable=self.modify_resolution_var).grid(row=0, column=1, sticky=tk.W, padx=5)
        
        resolution_options = [
            "原分辨率",
            "4K",
            "2K", 
            "1080p",
            "720p",
            "480p"
        ]
        resolution_combo = ttk.Combobox(resolution_frame, textvariable=self.resolution_var, 
                                       values=resolution_options, state="readonly", width=15)
        resolution_combo.grid(row=0, column=2, sticky=tk.W, padx=5)
        
        # 并行处理设置框架
        parallel_frame = ttk.LabelFrame(main_frame, text="并行处理设置", padding="5")
        parallel_frame.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5)
        
        # 并行数量选择
        ttk.Label(parallel_frame, text="并行数量:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
        parallel_spinbox = ttk.Spinbox(parallel_frame, from_=1, to=8, textvariable=self.parallel_count_var, width=10)
        parallel_spinbox.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
        
        # 显示推荐信息
        ttk.Label(parallel_frame, text=f"(推荐最大: 8)", foreground="gray").grid(row=0, column=2, sticky=tk.W, padx=5, pady=5)
        
        # 文件列表显示
        ttk.Label(main_frame, text="检测到的视频文件:").grid(row=4, column=0, sticky=tk.W, pady=5)
        
        # 创建文件列表框架
        list_frame = ttk.Frame(main_frame)
        list_frame.grid(row=5, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
        list_frame.columnconfigure(0, weight=1)
        list_frame.rowconfigure(0, weight=1)
        
        # 创建Treeview（表格）替代Listbox
        columns = ('filename', 'size', 'resolution', 'duration', 'fps', 'video_codec', 'audio_codec', 'status', 'path')
        self.file_treeview = ttk.Treeview(list_frame, columns=columns, show='headings', height=10)
        
        # 设置列标题
        self.file_treeview.heading('filename', text='文件名')
        self.file_treeview.heading('size', text='文件大小')
        self.file_treeview.heading('resolution', text='分辨率')
        self.file_treeview.heading('duration', text='时长')
        self.file_treeview.heading('fps', text='帧率')
        self.file_treeview.heading('video_codec', text='视频编码')
        self.file_treeview.heading('audio_codec', text='音频编码')
        self.file_treeview.heading('status', text='处理状态')
        self.file_treeview.heading('path', text='文件路径')
        
        # 设置列宽
        self.file_treeview.column('filename', width=150, minwidth=100)
        self.file_treeview.column('size', width=80, minwidth=60)
        self.file_treeview.column('resolution', width=100, minwidth=80)
        self.file_treeview.column('duration', width=80, minwidth=60)
        self.file_treeview.column('fps', width=60, minwidth=50)
        self.file_treeview.column('video_codec', width=80, minwidth=60)
        self.file_treeview.column('audio_codec', width=80, minwidth=60)
        self.file_treeview.column('status', width=100, minwidth=80)
        self.file_treeview.column('path', width=200, minwidth=150)
        
        # 添加滚动条
        tree_scrollbar_y = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.file_treeview.yview)
        tree_scrollbar_x = ttk.Scrollbar(list_frame, orient=tk.HORIZONTAL, command=self.file_treeview.xview)
        self.file_treeview.configure(yscrollcommand=tree_scrollbar_y.set, xscrollcommand=tree_scrollbar_x.set)
        
        # 布局
        self.file_treeview.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        tree_scrollbar_y.grid(row=0, column=1, sticky=(tk.N, tk.S))
        tree_scrollbar_x.grid(row=1, column=0, sticky=(tk.W, tk.E))
        
        # 配置标签颜色
        self.file_treeview.tag_configure('processing', foreground='blue')
        self.file_treeview.tag_configure('completed', foreground='green')
        self.file_treeview.tag_configure('failed', foreground='red')
        self.file_treeview.tag_configure('stopped', foreground='orange')
        
        # 进度条
        ttk.Label(main_frame, text="处理进度:").grid(row=6, column=0, sticky=tk.W, pady=5)
        self.progress_bar = ttk.Progressbar(main_frame, variable=self.progress_var, maximum=100)
        self.progress_bar.grid(row=6, column=1, sticky=(tk.W, tk.E), padx=5, pady=5)
        
        # 状态标签
        self.status_label = ttk.Label(main_frame, text="就绪")
        self.status_label.grid(row=7, column=0, columnspan=3, sticky=tk.W, pady=5)
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=8, column=0, columnspan=3, pady=10)
        
        # 开始处理按钮
        self.process_button = ttk.Button(button_frame, text="开始处理", command=self.start_processing)
        self.process_button.pack(side=tk.LEFT, padx=5)
        
        # 停止按钮
        self.stop_button = ttk.Button(button_frame, text="停止", command=self.stop_processing, state=tk.DISABLED)
        self.stop_button.pack(side=tk.LEFT, padx=5)
        
        # 清空列表按钮
        ttk.Button(button_frame, text="清空列表", command=self.clear_list).pack(side=tk.LEFT, padx=5)
    
    def select_input_folder(self):
        """选择输入文件夹"""
        folder = filedialog.askdirectory(title="选择包含视频文件的文件夹")
        if folder:
            self.input_folder_var.set(folder)
            self.scan_video_files()
    
    def select_output_folder(self):
        """选择输出文件夹"""
        folder = filedialog.askdirectory(title="选择输出文件夹")
        if folder:
            self.output_folder_var.set(folder)
    
    def scan_video_files(self):
        """扫描视频文件"""
        input_folder = self.input_folder_var.get()
        if not input_folder:
            return
        
        try:
            # 获取所有视频文件路径
            video_files = self.file_validator.scan_video_files(input_folder)
            if not video_files:
                self.status_label.config(text="未检测到视频文件")
                return
            
            # 显示扫描进度
            self.status_label.config(text=f"正在解析 {len(video_files)} 个视频文件信息...")
            self.root.update_idletasks()
            
            # 使用多线程并行解析视频信息
            self.parse_video_info_parallel(video_files)
            
        except Exception as e:
            messagebox.showerror("错误", f"扫描文件时出错: {str(e)}")
    
    def parse_video_info_parallel(self, video_files):
        """并行解析视频文件信息"""
        # 获取用户设置的进程数量
        parallel_count = self.parallel_count_var.get()
        
        # 验证进程数量
        if parallel_count < 1:
            parallel_count = 1
        elif parallel_count > 8: # 最大不超过8个
            parallel_count = 8
        
        # 启动进程管理器
        self.process_manager.start(max_workers=parallel_count)
        
        # 初始化解析状态
        self.parse_completed_count = 0
        self.parse_total_files = len(video_files)
        self.parse_video_info_list = []
        self.parse_processing = True
        
        # 提交所有解析任务
        for file_path in video_files:
            self.process_manager.submit_task({
                'type': 'parse_video',
                'file_path': file_path
            })
        
        # 启动解析进度更新
        self.update_parse_progress()
    
    def update_parse_progress(self):
        """更新解析进度"""
        try:
            # 从进程管理器获取结果
            while True:
                result = self.process_manager.get_result(timeout=0.01)
                if result is None:
                    break
                
                self.batch_update_parse_progress([result])
            
            # 检查是否所有任务都完成了
            if self.parse_processing and self.parse_completed_count == self.parse_total_files:
                print(f"[解析完成] 总共解析了 {self.parse_completed_count} 个文件")
                print(f"[解析完成] 解析结果列表长度: {len(self.parse_video_info_list)}")
                
                # 显示统计信息
                if self.parse_video_info_list:
                    total_size = sum(info['size'] for info in self.parse_video_info_list)
                    total_size_str = self.file_manager.format_file_size(total_size)
                    avg_size_str = self.file_manager.format_file_size(total_size // len(self.parse_video_info_list))
                    self.status_label.config(text=f"检测到 {len(self.parse_video_info_list)} 个视频文件 | 总大小: {total_size_str} | 平均: {avg_size_str}")
                else:
                    self.status_label.config(text="未检测到视频文件")
                
                # 清理解析状态
                self.parse_processing = False
                self.process_manager.stop()
                print(f"[解析完成] 解析任务完全结束")
                return
            
            # 继续监听结果
            self.root.after(100, self.update_parse_progress)
                
        except Exception as e:
            print(f"[GUI] 更新解析进度时发生错误: {e}")
            import traceback
            traceback.print_exc()
            self.root.after(100, self.update_parse_progress)
    
    def batch_update_parse_progress(self, messages):
        """批量更新解析进度"""
        for msg in messages:
            if msg['type'] == 'parse_start':
                # 文件开始解析
                self.status_label.config(text=f"正在解析视频信息... {self.parse_completed_count}/{self.parse_total_files}")
                self.root.update_idletasks()
                
            elif msg['type'] == 'parse_complete':
                # 文件解析完成
                self.parse_completed_count += 1
                
                if msg['success']:
                    self.parse_video_info_list.append(msg['result'])
                    # 立即更新文件列表
                    self.update_file_list_with_info(self.parse_video_info_list)
                
                # 更新进度
                self.status_label.config(text=f"正在解析视频信息... {self.parse_completed_count}/{self.parse_total_files}")
                self.root.update_idletasks()
    
    def update_file_list_with_info(self, video_info_list):
        """使用解析的信息更新文件列表"""
        # 清空现有列表
        self.file_treeview.delete(*self.file_treeview.get_children())
        self.file_items.clear()
        self.file_status.clear()
        self.processing_files.clear()
        
        # 按路径排序，保持文件顺序一致
        video_info_list.sort(key=lambda x: x['path'])
        
        # 添加文件到列表
        for info in video_info_list:
            if info is None:
                continue
                
            file_path = info['path']
            filename = os.path.basename(file_path)
            size_str = self.file_manager.format_file_size(info['size'])
            duration_str = self.format_duration(info['duration'])
            fps_str = f"{info['fps']:.1f}"
            audio_codec = info['audio_codec'] if info['has_audio'] else "无音频"
            
            # 插入到Treeview
            item = self.file_treeview.insert('', 'end', values=(
                filename,
                size_str,
                info['resolution'],
                duration_str,
                fps_str,
                info['video_codec'],
                audio_codec,
                "待处理",
                file_path
            ))
            
            # 存储映射关系
            self.file_items[file_path] = item
            self.file_status[file_path] = "待处理"
        
        # 强制更新GUI
        self.root.update_idletasks()
    
    def clear_list(self):
        """清空文件列表"""
        self.file_treeview.delete(*self.file_treeview.get_children())
        self.file_items.clear()
        self.file_status.clear()
        self.processing_files.clear()
        self.completed_count = 0
        self.total_files = 0
        self.progress_var.set(0)
        self.status_label.config(text="就绪")
    
    def format_duration(self, seconds):
        """格式化时长显示"""
        if seconds is None or seconds <= 0:
            return "N/A"
        
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        
        if hours > 0:
            return f"{hours:02d}:{minutes:02d}:{secs:02d}"
        else:
            return f"{minutes:02d}:{secs:02d}"
    
    def update_file_status(self, file_path, status, color="black"):
        """更新文件处理状态"""
        current_time = datetime.now().strftime("%H:%M:%S")
        if file_path in self.file_items:
            item = self.file_items[file_path]
            # 获取当前行的所有值
            current_values = list(self.file_treeview.item(item, 'values'))
            # 更新状态列（第8列，索引7）
            current_values[7] = status
            # 更新表格项
            self.file_treeview.item(item, values=current_values)
            # 更新状态字典
            self.file_status[file_path] = status
            
            # 更新处理中文件集合
            if status == "处理中":
                self.processing_files.add(file_path)
                self.file_treeview.item(item, tags=('processing',))
            elif status == "已完成":
                self.processing_files.discard(file_path)
                self.file_treeview.item(item, tags=('completed',))
            elif status == "失败":
                self.processing_files.discard(file_path)
                self.file_treeview.item(item, tags=('failed',))
            elif status == "已停止":
                self.processing_files.discard(file_path)
                self.file_treeview.item(item, tags=('stopped',))
            else:
                self.processing_files.discard(file_path)
                self.file_treeview.item(item, tags=())
            
            # 确保表格项可见
            self.file_treeview.see(item)
            # 强制更新表格显示
            self.file_treeview.update_idletasks()
        else:
            print(f"[GUI] 警告: 文件 {os.path.basename(file_path)} 不在文件列表中 - {current_time}")
    
    def get_status_summary(self):
        """获取状态统计摘要"""
        completed = sum(1 for status in self.file_status.values() if status == "已完成")
        failed = sum(1 for status in self.file_status.values() if status == "失败")
        processing = len(self.processing_files)
        pending = self.total_files - completed - failed - processing
        return completed, failed, processing, pending
    
    def start_processing(self):
        """开始处理"""
        if not self.input_folder_var.get() or not self.output_folder_var.get():
            messagebox.showwarning("警告", "请选择输入和输出文件夹")
            return
        
        # 检查线程数量是否超过CPU核心数
        parallel_count = self.parallel_count_var.get()
        if parallel_count < 1:
            parallel_count = 1
        elif parallel_count > 8: # 最大不超过8个
            parallel_count = 8
        
        # 获取文件列表
        input_folder = self.input_folder_var.get()
        output_folder = self.output_folder_var.get()
        
        try:
            video_files = self.file_validator.scan_video_files(input_folder)
            if not video_files:
                messagebox.showinfo("信息", "未找到视频文件")
                return
            
            print(f"开始处理 {len(video_files)} 个视频文件")
            print(f"输出文件夹: {output_folder}")
            print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            # 禁用开始按钮，启用停止按钮
            self.process_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
            
            # 重置停止标志
            self.stop_processing_flag = False
            
            # 重置处理状态
            self.completed_count = 0
            self.total_files = len(video_files)
            self.progress_var.set(0)
            self.first_update_time = None  # 重置第一次更新时间
            self.processing_start_time = None  # 重置处理开始时间
            self.processing = True  # 设置处理标志，用于资源监控
            
            # 更新状态
            self.status_label.config(text=f"开始处理 {len(video_files)} 个文件...")
            
            # 使用线程池进行并行处理
            self.process_videos_parallel(video_files, output_folder)
            
            # 启动进度更新（在这里初始化processing_start_time）
            self.processing_start_time = time.time()
            self.update_progress()
            
        except Exception as e:
            messagebox.showerror("错误", f"处理时出错: {str(e)}")
            self.reset_buttons()
    
    def process_videos_parallel(self, video_files, output_folder):
        """并行处理视频文件"""
        parallel_count = self.parallel_count_var.get()
        
        # 验证进程数量
        if parallel_count < 1:
            parallel_count = 1
        elif parallel_count > 8: # 最大不超过8个
            parallel_count = 8
        
        # 启动进程管理器
        self.process_manager.start(max_workers=parallel_count)
        
        # 初始化处理状态
        self.completed_count = 0
        self.total_files = len(video_files)
        self.processing_start_time = time.time()
        self.first_update_time = None
        self.processing = True
        
        # 提交所有处理任务
        target_resolution = self.resolution_var.get() if self.modify_resolution_var.get() else "原分辨率"
        
        # 添加调试信息
        print(f"[分辨率设置] 修改分辨率: {self.modify_resolution_var.get()}")
        print(f"[分辨率设置] 选择的分辨率: {self.resolution_var.get()}")
        print(f"[分辨率设置] 最终使用的分辨率: {target_resolution}")
        
        for file_path in video_files:
            self.process_manager.submit_task({
                'type': 'process_video',
                'file_path': file_path,
                'output_folder': output_folder,
                'target_resolution': target_resolution,
                'save_audio': self.save_audio_var.get(),
                'save_video': self.save_video_var.get(),
                'save_subtitles': self.save_subtitles_var.get(),
                'remove_subtitles': self.remove_subtitles_var.get(),
                'remove_hardcoded_subtitles': self.remove_hardcoded_subtitles_var.get()
            })
        
        # 启动进度更新
        self.update_progress()
    
    def update_progress(self):
        """批量更新进度条和状态，减少UI刷新频率"""
        try:
            # 记录处理开始时间（如果还没有记录）
            if self.processing_start_time is None:
                self.processing_start_time = time.time()
                start_datetime = datetime.now().strftime("%H:%M:%S.%f")[:-3]
            
            # 批量处理队列中的消息
            messages = []
            try:
                while True:
                    result = self.process_manager.get_result(timeout=0.01)
                    if result is None:
                        break
                    messages.append(result)
            except:
                pass
            
            # 批量更新UI
            if messages:
                self.batch_update_ui(messages)
            
            # 检查是否所有任务都完成了
            if self.processing and self.completed_count == self.total_files:
                # 所有文件处理完成
                self.progress_var.set(100)
                completed, failed, processing, pending = self.get_status_summary()
                self.status_label.config(text=f"处理完成 - 成功: {completed}, 失败: {failed}, 待处理: {pending}")
                self.processing = False  # 清除处理标志
                self.process_manager.stop()
                self.reset_buttons()
                return
            
            # 继续检查，直到处理完完成信号
            self.root.after(500, self.update_progress)
                
        except Exception as e:
            print(f"[GUI] 更新进度时发生错误: {e}")
            self.root.after(500, self.update_progress)
    
    def batch_update_ui(self, messages):
        """批量更新UI，减少刷新次数"""
        for update in messages:
            if update['type'] == 'file_start':
                # 文件开始处理
                if self.first_update_time is None:
                    self.first_update_time = time.time()
                    first_update_datetime = datetime.now().strftime("%H:%M:%S.%f")[:-3]
                    if self.processing_start_time is not None:
                        delay = self.first_update_time - self.processing_start_time
                
                self.update_file_status(update['file_path'], "处理中")
                
            elif update['type'] == 'file_complete':
                # 文件处理完成
                file_path = update['file_path']
                worker_id = update['worker_id']
                success = update['success']
                
                if success:
                    self.update_file_status(file_path, "已完成")
                    self.completed_count += 1
                else:
                    self.update_file_status(file_path, "失败")
                    self.completed_count += 1
                    error_msg = f"处理文件 {os.path.basename(file_path)} 时出错: {update['error']}"
                
                # 更新进度条
                progress = (self.completed_count / self.total_files) * 100
                self.progress_var.set(progress)
                
            elif update['type'] == 'complete':
                # 所有文件处理完成
                end_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                if self.processing_start_time is not None:
                    total_duration = time.time() - self.processing_start_time
                    if self.first_update_time:
                        first_update_delay = self.first_update_time - self.processing_start_time
                self.progress_var.set(100)
                completed, failed, processing, pending = self.get_status_summary()
                self.status_label.config(text=f"处理完成 - 成功: {completed}, 失败: {failed}, 待处理: {pending}")
                self.processing = False  # 清除处理标志
                self.reset_buttons()
                return
                
            elif update['type'] == 'stopped':
                self.status_label.config(text=update['message'])
                self.reset_buttons()
                return
        
        # 批量更新状态标签（只在有消息时更新）
        if messages:
            completed, failed, processing, pending = self.get_status_summary()
            status_text = f"处理中: {processing}, 已完成: {completed}, 失败: {failed}, 待处理: {pending}, 总计: {self.total_files}"
            self.status_label.config(text=status_text)
            self.root.update_idletasks()  # 强制更新GUI
    
    def process_videos(self, video_files, output_folder):
        """处理视频文件（保留原方法用于兼容性）"""
        self.process_videos_parallel(video_files, output_folder)
    
    def stop_processing(self):
        """停止处理"""
        self.stop_processing_flag = True
        self.status_label.config(text="正在停止处理...")
        self.stop_button.config(state=tk.DISABLED)
        
        # 停止进程管理器
        self.process_manager.stop()
        
        # 更新文件状态为已停止
        for file_path in self.processing_files:
            self.update_file_status(file_path, "已停止")
        
        self.processing_files.clear()
        self.processing = False
        self.reset_buttons()
    
    def reset_buttons(self):
        """重置按钮状态"""
        self.process_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED) 